package com.white.camlib;

import android.content.Context;
import android.util.AttributeSet;
import android.view.TextureView;

/**
 * Created by ytf on 2021/6/3 003.
 * Description:
 */

public class AutoFitTextureView extends TextureView {


    private int ratioWidth = 16;
    private int ratioHeight = 9;

    public AutoFitTextureView(Context context) {
        this(context, null);
    }

    public AutoFitTextureView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoFitTextureView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setAspectRatio(int w, int h) {
        if (w <= 0 || h <= 0) {
            throw new IllegalArgumentException("Size cannot be negative or zero.");
        }
        ratioWidth = w;
        ratioHeight = h;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (ratioWidth == 0 || ratioHeight == 0) {
            setMeasuredDimension(width, height);
        } else {
            if (width < height * ratioWidth * 1.0f / ratioHeight) {
                setMeasuredDimension(width, (int)(width * ratioHeight * 1.0f / ratioWidth));
            } else {
                setMeasuredDimension((int)(height * ratioWidth * 1.0f / ratioHeight), height);
            }
        }
    }
}
